package middleware

import (
	"log"
	"strings"

	"github.com/gin-gonic/gin"

	"internal-net-bridge-server/internal/config"
	"internal-net-bridge-server/internal/models"
	"internal-net-bridge-server/internal/services"
)

// AuthMiddleware JWT认证中间件
func AuthMiddleware() gin.HandlerFunc {
	authService := services.NewAuthService()

	return func(c *gin.Context) {
		// 从请求头获取token
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			models.SendUnauthorized(c, "缺少认证token")
			c.Abort()
			return
		}

		// 检查 Bearer 前缀
		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || parts[0] != "Bearer" {
			models.SendUnauthorized(c, "认证格式错误")
			c.Abort()
			return
		}

		token := parts[1]

		// 验证token
		user, err := authService.ValidateToken(token)
		if err != nil {
			models.SendUnauthorized(c, "认证失败: "+err.Error())
			c.Abort()
			return
		}

		// 将用户信息存储到上下文中
		c.Set("user", user)
		c.Set("user_id", user.ID)
		c.Set("token", token)

		c.Next()
	}
}

// UnifiedAuthMiddleware 统一认证中间件 - 根据配置决定是否启用认证
func UnifiedAuthMiddleware() gin.HandlerFunc {
	authService := services.NewAuthService()

	return func(c *gin.Context) {
		// 检查是否启用认证
		if !config.IsAuthEnabled() {
			// 认证禁用时，设置默认用户ID
			defaultUserID := uint(1)
			log.Printf("⚠️  认证已禁用，使用默认用户ID: %d", defaultUserID)
			c.Set("user_id", defaultUserID)
			c.Next()
			return
		}

		// 启用认证时，执行完整的JWT验证
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			models.SendUnauthorized(c, "缺少认证token")
			c.Abort()
			return
		}

		// 检查 Bearer 前缀
		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || parts[0] != "Bearer" {
			models.SendUnauthorized(c, "认证格式错误")
			c.Abort()
			return
		}

		token := parts[1]

		// 验证token
		user, err := authService.ValidateToken(token)
		if err != nil {
			models.SendUnauthorized(c, "认证失败: "+err.Error())
			c.Abort()
			return
		}

		// 将用户信息存储到上下文中
		c.Set("user", user)
		c.Set("user_id", user.ID)
		c.Set("token", token)

		c.Next()
	}
}

// OptionalAuthMiddleware 可选认证中间件（如果有token则验证，没有则跳过）
func OptionalAuthMiddleware() gin.HandlerFunc {
	authService := services.NewAuthService()

	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.Next()
			return
		}

		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || parts[0] != "Bearer" {
			c.Next()
			return
		}

		token := parts[1]
		user, err := authService.ValidateToken(token)
		if err == nil {
			c.Set("user", user)
			c.Set("user_id", user.ID)
			c.Set("token", token)
		}

		c.Next()
	}
}

// AdminMiddleware 管理员权限中间件
func AdminMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		user, exists := c.Get("user")
		if !exists {
			models.SendUnauthorized(c, "未认证用户")
			c.Abort()
			return
		}

		userModel := user.(*models.User)
		if userModel.Role != "admin" {
			models.SendForbidden(c, "权限不足")
			c.Abort()
			return
		}

		c.Next()
	}
}

// GetCurrentUser 从上下文获取当前用户
func GetCurrentUser(c *gin.Context) (*models.User, bool) {
	user, exists := c.Get("user")
	if !exists {
		return nil, false
	}
	return user.(*models.User), true
}

// GetCurrentUserID 从上下文获取当前用户ID
func GetCurrentUserID(c *gin.Context) (uint, bool) {
	userID, exists := c.Get("user_id")
	if !exists {
		return 0, false
	}
	return userID.(uint), true
}

// GetCurrentToken 从上下文获取当前token
func GetCurrentToken(c *gin.Context) (string, bool) {
	token, exists := c.Get("token")
	if !exists {
		return "", false
	}
	return token.(string), true
}
